// OverlayInputPlugin.ts
import type { App } from "vue";
import { createApp, h, reactive, nextTick } from "vue";
import { Popup, Field, Button } from "vant";

type OverlayState = {
  show: boolean;
  value: string;
  callback: ((val: string) => void) | null;
};

export default {
  install(
    app: App,
    options?: {
      style?: Record<string, string>;
      buttonStyle?: Record<string, string>;
    }
  ) {
    const state = reactive<OverlayState>({
      show: false,
      value: "",
      callback: null,
    });

    let overlayFieldRef: HTMLTextAreaElement | null = null;

    function isLandscape() {
      return window.innerWidth > window.innerHeight;
    }

    function isPC() {
      return (
        !("ontouchstart" in window) ||
        /Windows|Macintosh/i.test(navigator.userAgent)
      );
    }

    function isTextInput(el: HTMLInputElement | HTMLTextAreaElement) {
      if (el instanceof HTMLTextAreaElement) return true;
      if (el instanceof HTMLInputElement) {
        const type = (el.type || "text").toLowerCase();
        const allowedTypes = [
          "text",
          "search",
          "password",
          "email",
          "url",
          "tel",
          "number",
        ];
        return allowedTypes.includes(type);
      }
      return false;
    }

    function submitOverlayValue() {
      overlayFieldRef?.blur();
      nextTick(() => {
        state.callback?.(state.value);
        state.show = false;
      });
    }

    // 输入框 focus 监听
    document.addEventListener("focusin", (e) => {
      if (!isLandscape() || isPC()) return;

      const target = e.target;
      if (
        !(
          target instanceof HTMLInputElement ||
          target instanceof HTMLTextAreaElement
        )
      )
        return;
      if (!isTextInput(target)) return;

      if (state.show) return;

      state.value = target.value;
      state.callback = (val) => {
        target.value = val;
        target.dispatchEvent(new Event("input", { bubbles: true }));
      };

      state.show = true;
      nextTick(() => overlayFieldRef?.focus());
    });

    // 遮罩层组件
    const OverlayComponent = {
      setup() {
        return () =>
          h(
            Popup,
            {
              show: state.show,
              "onUpdate:show": (v: boolean) => (state.show = v),
              position: "bottom",
              lockScroll: true,
              style: {
                height: "100%",
                padding: "5vmin",
                boxSizing: "border-box",
              },
            },
            {
              default: () => [
                h(
                  "div",
                  {
                    class: "overlay-input-container",
                    style: {
                      display: "flex",
                      alignItems: "flex-start",
                      gap: "8px", // 输入框和按钮之间间距
                    },
                  },
                  [
                    // 输入框
                    h(Field, {
                      class: "overlay-field",
                      ref: (el: any) =>
                        (overlayFieldRef =
                          el?.$el.querySelector("textarea") || null),
                      modelValue: state.value,
                      "onUpdate:modelValue": (v: string) => (state.value = v),
                      autofocus: true,
                      type: "textarea",
                      autosize: true,
                      placeholder: "请输入...",
                      enterkeyhint: "done",
                      style: {
                        flex: 1, // 自适应宽度，占满剩余空间
                        paddingTop: "0px",
                        ...options?.style,
                      },
                      onKeydown: (e: KeyboardEvent) => {
                        if (e.key === "Enter") {
                          e.preventDefault();
                          submitOverlayValue();
                        }
                      },
                    }),
                    // 右侧完成按钮
                    h(
                      Button,
                      {
                        class: "overlay-complete-btn",
                        size: "small",
                        color: "white",
                        style: {
                          flexShrink: 0, // 固定宽度，不被压缩
                          background:
                            "linear-gradient(135deg, #FF0000 0%, #FF3A37 100%)",
                          width: "15vmin",
                          ...options?.buttonStyle,
                        },
                        onClick: (e: MouseEvent) => {
                          e.stopPropagation();
                          submitOverlayValue();
                        },
                      },
                      { default: () => "完成" }
                    ),
                  ]
                ),
              ],
            }
          );
      },
    };

    const overlayApp = createApp(OverlayComponent);
    overlayApp.use(Popup).use(Field).use(Button);
    const div = document.createElement("div");
    document.body.appendChild(div);
    overlayApp.mount(div);

    // 独立样式，避免污染页面
    const style = document.createElement("style");
    style.innerHTML = `
       .overlay-field:after{
        border:none !important;
      }
      .overlay-field .van-field__control{
         height: 50vmin !important;
      }
    `;
    document.head.appendChild(style);
  },
};
